﻿using System;
using System.Web;
using System.Web.Mvc;

namespace CodeCamp.Infrastructure
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public string Message { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool authorized = base.AuthorizeCore(httpContext);
            if (!authorized)
            {
                MvcApplication mvcApp = httpContext.ApplicationInstance as MvcApplication;
                if ((mvcApp != null) && (mvcApp.Logger != null))
                {
                    string url = null;
                    if (httpContext.ApplicationInstance.Request != null)
                        url = httpContext.ApplicationInstance.Request.Url.AbsolutePath;
                    mvcApp.Logger.WarnFormat(null, "User not authorized for \"{0}\"", url);
                }
            }
            return authorized;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if ((filterContext.Result != null) && filterContext.Result is System.Web.Mvc.HttpUnauthorizedResult)
            {
                var result = new ViewResult();
                result.ViewName = "NotAuthorized";
                result.MasterName = "";
                result.ViewBag.Message = this.Message;
                filterContext.Result = result;
            }
        }
    }
}